<!--
1.序号
2.姓名
3.性别
4.预约号码
5.状态 =》 已挂号，就诊中， 1：已挂号 2：就诊中 叫号===就诊中 4：过号
排序=》时间顺序，创建时间顺序
是否网上预约：0不是 1是
是=》 姓名(预)

预约号码中间四位数为 *

-->
<template>
    <div class="home">
        <!--        <el-container style="height: 100%;" direction="vertical">-->
        <!--            <el-header>李照权中医诊所</el-header>-->
        <el-main>
            <!-- 当前就诊 -->
            <el-card
                    class="box-card nowCard"
                    shadow="always"
                    style="width: 90%; margin: 0 auto;border-radius: 15px"
                    :body-style="{borderRadius:'30%', padding: '10px'}"
                    v-cloak>
                <span class="outPatient">当前就诊</span>
                <div>
                    <el-table
                            :data="nowPatient"
                            style="width: 99.9%;font-size: 45px;"
                            v-if="nowPatient"
                            :show-header=false
                            :cell-style="{fontWeight: 'bolder'}"
                            :row-style="{height: '100px', color: '#333'}"
                            empty-text="暂无就诊"
                            v-cloak
                    >
                        <el-table-column
                                align="center"
                                label="序号"
                                width="350"
                                v-cloak
                        >
                            <template slot-scope="scope">
                                <i class="el-icon-more"></i>
                            </template>
                        </el-table-column>
                        <el-table-column
                                align="center"
                                prop="name"
                                label="姓名"
                                v-cloak
                        >
                        </el-table-column>
<!--                        <el-table-column-->
<!--                                align="center"-->
<!--                                prop="number"-->
<!--                                label="预约号码"-->
<!--                                v-cloak-->
<!--                        >-->
<!--                            <template slot-scope="scope">-->
<!--                                <span> {{ scope.row.number | filNumber }} </span>-->
<!--                            </template>-->
<!--                        </el-table-column>-->
                        <el-table-column
                                align="center"
                                prop="state"
                                label="状态"
                                v-cloak
                        >
                            <template slot-scope="scope">
                                <el-tag
                                    style="margin-left: 30px"
                                        type="success"
                                        effect="dark"
                                        v-cloak
                                        size="medium"
                                        disable-transitions
                                >
                                    {{ scope.row.state | filStatus }}
                                </el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-table v-else
                              empty-text="暂无就诊">
                    </el-table>
                </div>
            </el-card>

            <!-- 间距，圆角，背景 表格内字体颜色#333
            状态变大
            表格头与背景色相同-->
            <div class="waitCard">
                <el-card
                        class="box-card"
                        shadow="always"
                        style="width: 90%; margin: 0 auto;border-radius: 10px;"
                        :body-style="{borderRadius:'30%', padding: '10px'}"
                        v-cloak>
                    <span class="waitPatient">等待就诊</span>
                    <el-table
                            show-overflow-tooltip
                            :data="showData"
                            v-if="showData"
                            style="width: 99.9%; font-size: 50px; font-style: normal;position: relative; left: 25px"
                            :show-header=true
                            :header-cell-style="{color:'#3790CC',height: '80px'}"
                            :row-style="{color: '#333',}"
                            :cell-style="{fontWeight: 'bolder'}"
                            ref="table"
                            empty-text="暂无预约"
                            v-cloak
                            size="medium"
                            :fit=true
                    >
                        <el-table-column
                                align="center"
                                prop="ids"
                                label="序号"
                                width="300"
                                v-cloak
                        >
                        </el-table-column>
                        <el-table-column
                                align="center"
                                prop="name"
                                label="姓名"
                                v-cloak
                        >
                            <template slot-scope="scope">
                                <span style="margin-left: 100px" class="elName">{{ scope.row.name, scope.row.isAppointment | filName }}</span>
                            </template>
                        </el-table-column>
<!--                        <el-table-column-->
<!--                                align="center"-->
<!--                                prop="number"-->
<!--                                label="预约号码"-->
<!--                                v-cloak-->
<!--                        >-->
<!--                            <template slot-scope="scope">-->
<!--                                <span> {{ scope.row.number | filNumber }} </span>-->
<!--                            </template>-->
<!--                        </el-table-column>-->
                        <el-table-column
                                align="center"
                                prop="state"
                                label="状态"
                                v-cloak
                        >
                            <template slot-scope="scope">
                                <el-tag
                                        v-if="scope.row.state === 2"
                                        type="success"
                                        effect="dark"
                                        v-cloak
                                        size="medium"
                                        disable-transitions
                                >
                                    {{ scope.row.state | filStatus }}
                                </el-tag>
                                <el-tag
                                        v-if="scope.row.state === 4"
                                        type="danger"
                                        effect="dark"
                                        v-cloak
                                        size="medium"
                                        disable-transitions
                                >
                                    {{ scope.row.state | filStatus }}
                                </el-tag>
                                <el-tag
                                        v-if="scope.row.state === 1"
                                        type="warning"
                                        effect="dark"
                                        v-cloak
                                        size="medium"
                                        disable-transitions
                                >
                                    {{ scope.row.state | filStatus }}
                                </el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-table v-else
                              empty-text="暂无预约">
                    </el-table>
                </el-card>
            </div>
        </el-main>
        <!--        </el-container>-->
    </div>
</template>

<script>
    export default {
        inject: ['reload'],
        name: 'Home',
        data() {
            return {
                nowPatient: null,// 就诊用户
                nowPatientIndex: -1,// 就诊用户下标
                tableData: [], // 接口获取的数据
                timer: [],// setInterval计时器
                timeout: [],// settimout计时器
                inter: null,
                outer: null,
                start: 0,
                end: 5, //一次显示多少条数据
                showData: null, // 显示的数据
                socket: {},
                socketAccount: 'electronicScreen',
                updateNum: -1,
                queryAll: [],
                isFullscreen: false
            }
        },
        methods: {
            // 设置当前就诊用户
            setNowPatient(item) {
                if (this.nowPatient.indexOf(item) === -1) {
                    this.nowPatient.push(item);
                }
            },
            // 过滤网上 线下预约
            filtePeriod(result) {
                //时间段ID排序
                result = result.sort(this.compare('appointmentPeriodId'))
                let map = {}
                for (let i = 0; i < result.length; i++) {
                    let ai = result[i]
                    if (!map[ai.appointmentPeriod]) {
                        map[ai.appointmentPeriod] = [ai]
                    } else {
                        map[ai.appointmentPeriod].push(ai)
                    }
                }
                let sortArr = []
                Object.keys(map).forEach(key => {
                    sortArr.push(map[key])
                })
                for (let i = 0; i < sortArr.length; i++) {
                    let itemArr = sortArr[i];
                    if (itemArr.length === 2) {
                        if (itemArr[0].isAppointment === 0) {
                            let temp = itemArr[0];
                            itemArr[0] = itemArr[1];
                            itemArr[1] = temp;
                            sortArr[i] = itemArr
                        }
                    }
                }

                let newArr = []
                for (let i = 0; i < sortArr.length; i++) {
                    let newArrItem = sortArr[i]
                    for (let j = 0; j < newArrItem.length; j++) {
                        newArr.push(newArrItem[j])
                    }
                }

                return newArr
            },
            compare(property) {
                return function (a, b) {
                    var value1 = a[property];
                    var value2 = b[property];
                    return value1 - value2;
                }
            },
            // 获取数据
            loadingPatient() {
                var _this = this;
                clearTimeout(_this.timeout)
                clearInterval(_this.timer)
                clearInterval(_this.inter)
                _this.timeout = [];
                _this.timer = [];
                _this.inter = null;
                _this.start = 0;
                _this.end = 5;
                _this.$axios.get('https://mp.wwtsz.com:8812/manager/electronicScreen').then(res => {
                    _this.queryAll = res.data.result;
                    let newArr = _this.filtePeriod(res.data.result)
                    // 过号数组
                    let passArr = new Array();
                    let index = 0;
                    _this.tableData = [];
                    _this.showData = [];
                    _this.nowPatient = [];
                    newArr.map(item => {
                        if (item.state === 4) {
                            passArr[index] = item;
                            index++;
                        } else if (item.state === 2) {
                            _this.setNowPatient(item)
                        } else if (item.state === 3) {

                        } else if (item.state === -1) {

                        } else {
                            _this.tableData.push(item)
                        }
                    })
                    _this.tableData = _this.tableData.concat(passArr)
                    _this.tableData = _this.delPatient(_this.tableData)
                    let idsIndex = 1;
                    _this.tableData.map(item => {
                        item.ids = -1;
                        if (item.id > 0) {
                            item.ids = idsIndex;
                            idsIndex++;
                        }
                        return item;
                    })
                    _this.showData = _this.tableData.slice(0, _this.end)
                    _this.controInter()
                }).catch(err => {
                    console.log(err)
                })
            },
            //删除就诊元素
            delPatient(arr) {
                for (let i = 0; i < arr.length; i++) {
                    if (arr[i].state === 2) {
                        this.setNowPatient(arr[i])
                        arr.splice(i, 1)
                    }
                }
                return arr;
            },
            // 数据滚动
            rollData() {
                const _this = this
                if (_this.tableData.length > _this.end) {
                    _this.inter = setInterval(() => {
                        _this.start++;
                        _this.end++;
                        _this.showData = _this.tableData.slice(_this.start, _this.end);
                        if (_this.end === _this.tableData.length) {
                            _this.timeout[0] = setTimeout(() => {
                                // _this.inter = null;
                                // _this.start = 0;
                                // _this.end = 5;
                                _this.loadingPatient();
                                // _this.reload();
                                // location.reload();
                            }, 1000 * 5)
                        }
                    }, 1000 * 5)
                }
            },
            // 全局interval
            controInter() {
                const _this = this;
                // _this.timer[0] = setInterval(() => {
                _this.rollData()
                // }, 1000 * 30)
            },
            // 呼叫当前就诊用户
            callUser(item) {
                const _this = this;
                if (item.number) {
                    _this.speckText("请" + item.name + "到101室就诊")
                }
            },
            openSocket: function () {
              let _this = this
              let socketUrl="http://mp.wwtsz.com:8813/ws/" + this.socketAccount;
              socketUrl = socketUrl.replace("https","wss").replace("http","ws");

              if(typeof(WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
              }else{
                console.log("您的浏览器支持WebSocket");
                var lockReconnect = false;//避免重复连接
                var ws;
                var tt;
                //创建链接
                createWebSocket();
                //创建链接
                function createWebSocket() {
                  try {
                    ws = new WebSocket(socketUrl);
                    // 初始化链接
                    init();
                  } catch(e) {
                    console.log('catch'+e);
                    reconnect(socketUrl);
                  }
                }

                /**
                 * 初始化链接
                 */
                function init() {
                  ws.onclose = function () {
                    reconnect(socketUrl);
                  };
                  ws.onerror = function() {
                    reconnect(socketUrl);
                  };
                  ws.onopen = function () {
                    ws.send("连接成功");
                    //心跳检测重置
                    heartCheck.start();
                  };
                  ws.onmessage = function (event) {
                    heartCheck.start();
                    //拿到任何消息都说明当前连接是正常的
                    //实时添加消息
                    if (_this.isJson(event.data)) {
                      let data = JSON.parse(event.data)
                      if (data.contentText === 'update') {
                        for (let i = 0; i < _this.queryAll.length; i++) {
                          var item = _this.queryAll[i];
                          if (item.number === data.number) {
                            let name = item.name
                            // _this.speckText("请" + item.name + "到101室就诊")
                            _this.$axios.get('https://mp.wwtsz.com:8812/manager/doctor/check?doctorId=' + item.doctorId)
                                .then(res => {
                                  _this.speckText("请" + name + "到" + res.data.result.department + "室就诊")
                                })
                          }
                        }
                        _this.loadingPatient()
                      }
                    }
                  }
                }

                var lockReconnect = false;//避免重复连接
                //重试连接socket
                function reconnect(wsUrl) {
                  if(lockReconnect) {
                    return;
                  };
                  lockReconnect = true;
                  //没连接上会一直重连，设置延迟避免请求过多
                  tt && clearTimeout(tt);
                  tt = setTimeout(function () {
                    createWebSocket(wsUrl);
                    lockReconnect = false;
                  }, 180000);
                }
                //心跳检测
                var heartCheck = {
                  timeout: 30000,
                  timeoutObj: null,
                  serverTimeoutObj: null,
                  start: function(){
                    var self = this;
                    this.timeoutObj && clearTimeout(this.timeoutObj);
                    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
                    this.timeoutObj = setTimeout(function(){
                      //这里发送一个心跳，后端收到后，返回一个心跳消息，
                      //onmessage拿到返回的心跳就说明连接正常
                      ws.send("连接成功");
                      self.serverTimeoutObj = setTimeout(function() {
                        console.log(ws);
                        ws.close();
                      }, self.timeout);
                    }, this.timeout)
                  }
                }
              }
            },
            closeSocket: function () {
                this.socket.close()
            },
            sendMessage: function () {
                let _this = this
                if (typeof (WebSocket) == "undefined") {
                    console.log("您的浏览器不支持WebSocket");
                } else {
                    console.log("发送消息")
                    _this.socket.send('{"toUserId":"' + 'all' + '","contentText":"' + 'update' + '"}');
                }
            },
            isJson: function (str) {
                if (typeof str == 'string') {
                    try {
                        let obj = JSON.parse(str);
                        if (typeof obj == 'object' && obj) {
                            return true;
                        } else {
                            return false;
                        }

                    } catch (e) {
                        // console.log('error：'+str+'!!!'+e);
                        return false;
                    }
                }
                console.log('It is not a string!')
            },
            speckText(str) {
                let utterance = new SpeechSynthesisUtterance();
                utterance.text = str;
                utterance.lang = 'zh';
                utterance.rate = 0.6;
                speechSynthesis.speak(utterance)

                // let url = "http://tts.baidu.com/text2audio?lan=zh&ie=UTF-8&spd=3&text=" + encodeURI(str);
                // let n = new Audio(url);
                // n.src = url;
                // n.play();
            },
        },
        created() {
            this.loadingPatient()
            this.openSocket()

        },
        filters: {
            //状态栏过滤器
            filStatus(value) {
                if (value === 1) {
                    return '已挂号'
                } else if (value === 2) {
                    return '就诊中'
                } else if (value === 4) {
                    return '已过号'
                }
            },
            //用户名过滤
            filName(name, status) {
                if (status === 1) {
                    return name + '(预)'
                } else {
                    return name
                }
            },
            //预约号码过滤
            filNumber(number) {
                var arr = number.split('')
                for (let i = 2; i < arr.length - 2; i++) {
                    arr[i] = '*'
                }
                return arr.join('')
            }
        },
        beforeDestroy() {
            const _this = this;
            clearTimeout(_this.timeout)
            clearInterval(_this.timer)
            clearInterval(_this.inter)
            _this.timeout = [];
            _this.timer = [];
            _this.inter = null;
            _this.closeSocket();
        },
        destroyed() {
            this.closeSocket();
        },
        beforeCreate() {
            document.querySelector('body').setAttribute('style', 'margin: 0 auto; width: 100%;background-color:#4f79f5;');
        },
    }
</script>

<style>
    * {
      font-family: 楷体;
    }
    .nowCard {
        margin-top: 30px
    }

    ::-webkit-scrollbar {
        width: 0 !important;
    }

    .el-tag {
        position: relative;
        top: -15px;
        font-weight: bold;
        transform: scale(2.0, 2.0);
    }

    .el-table__fixed, .el-table__fixed-right {
        height: 100% !important;
    }

    .outPatient {
        color: #3790CC;
        font-weight: bolder;
        text-align: center;
        letter-spacing: 2.8pt;
        float: left;
        font-size: 30px;
    }

    .waitPatient {
        float: left;
        color: #CC9A37;
        font-weight: bold;
        text-align: center;
        letter-spacing: 2.8pt;
        word-spacing: 1.4pt;
        font-size: 30px;
    }
    .el-table .cell {
        white-space: nowrap;
    }

    .el-table__header .cell{
        padding: 15px;
        height: 60px;
    }

    .el-table__row .cell {
        /*margin-left: 30px;*/
        padding: 30px;
        height: 80px;
    }


    .home .el-container {
        /*设置内部填充为0，几个布局元素之间没有间距*/
        padding: 0px;
        /*外部间距也是如此设置*/
        margin: 0px;
        /*统一设置高度为100%*/
        height: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .el-table__footer-wrapper, .el-table__header-wrapper {
        overflow: auto;
    }


    /* 解决饿了么ui 滚动闪烁BOG */
    .el-table__footer-wrapper, .el-table__header-wrapper, .dkcard .el-table {
        /* overflow: auto !important; */
        width: calc(100% - 2px) !important;
    }

    .el-table__body, .el-table__footer, .el-table__header {
        width: calc(100% - 2px) !important;
    }

    .el-table .warning-row {
        background: oldlace;
    }

    .el-table .success-row {
        background: #f0f9eb;
    }

    .el-main {
        color: #333;
        text-align: center;
        margin-top: -50px;
    }

    body > .el-container {
        margin-bottom: 40px;
    }

    .el-table::before {
        z-index: inherit;
    }

    .el-table tbody tr:hover > td {
        background-color: #ffffff !important
    }

    [v-cloak] {
        display: none;
    }

    .waitCard {
        margin-top: 30px;
        height: calc(100% - 40px);
    }
</style>
